import 'package:after_layout/after_layout.dart';
import 'package:flutter/material.dart';

class SelfHomePage extends StatelessWidget {
  const SelfHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double rpx = MediaQuery.of(context).size.width / 750;
    return Scaffold(
      body: Container(
        child: HomeMain(rpx: rpx),
      ),
    );
  }
}

class HomeMain extends StatefulWidget {
  const HomeMain({Key? key, required this.rpx}) : super(key: key);

  final double rpx;

  @override
  State<HomeMain> createState() => _HomeMainState();
}

class _HomeMainState extends State<HomeMain> with TickerProviderStateMixin {
  double extraPicHeight = 0;

  late BoxFit fitType;
  late double prev_dy;
  late AnimationController animationController;
  late Animation<double> anim;
  late TabController tabController;
  double expendHeight = 300;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    fitType = BoxFit.fitWidth;
    prev_dy = 0;
    animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 300));
    anim = Tween(begin: 0.0, end: 0.0).animate(animationController);
    tabController = TabController(length: 3, vsync: this);
  }

  updatePicHeight(changed) {
    if (prev_dy == 0) {
      prev_dy = changed;
    }
    extraPicHeight += changed - prev_dy;

    if (extraPicHeight >= 200 * widget.rpx) {
      fitType = BoxFit.fitHeight;
    } else {
      fitType = BoxFit.fitWidth;
    }

    setState(() {
      prev_dy = changed;
      extraPicHeight = extraPicHeight;
      fitType = fitType;
    });
  }

  updateExpendheight(height) {
    setState(() {
      expendHeight = height;
    });
  }

  runAnimate() {
    setState(() {
      anim = Tween(begin: extraPicHeight, end: 0.0).animate(animationController)
        ..addListener(() {
          if (extraPicHeight >= 200 * widget.rpx) {
            fitType = BoxFit.fitHeight;
          } else {
            fitType = BoxFit.fitWidth;
          }
          setState(() {
            extraPicHeight = anim.value;
            fitType = fitType;
          });
        });
    });
    prev_dy = 0;
  }

  @override
  Widget build(BuildContext context) {
    double rpx = MediaQuery.of(context).size.width / 750;
    return Listener(
      onPointerMove: (result) {
        updatePicHeight(result.position.dy);
      },
      onPointerUp: (_) {
        runAnimate();
        animationController.forward(from: 0);
      },
      child: CustomScrollView(
        physics: ClampingScrollPhysics(),
        slivers: [
          SliverAppBar(
            pinned: true,
            floating: true,
            actions: [Icon(Icons.more_horiz)],
            leading: IconButton(
              icon: IconButton(
                icon: Icon(Icons.arrow_back),
                onPressed: () {},
              ),
              onPressed: () {},
            ),
            bottom: PreferredSize(
                preferredSize: Size.fromHeight(50),
                child: TabBar(
                  controller: tabController,
                  tabs: [
                    Text("作品 91"),
                    Text("动态 91"),
                    Text("喜欢 91"),
                  ],
                )),
            // expandedHeight: 510 * rpx + extraPicHeight,
            expandedHeight: expendHeight + extraPicHeight,
            flexibleSpace: FlexibleSpaceBar(
                background: TopBarWithCallBack(
              extraPicHeight: extraPicHeight,
              fitType: fitType,
              updateHeight: updateExpendheight,
            )),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate((context, index) {
              return Container(
                height: 30,
                alignment: Alignment.centerLeft,
                color: Colors.blueAccent,
                child: Text("This is itm $index"),
                margin: EdgeInsets.symmetric(
                    horizontal: 20 * rpx, vertical: 10 * rpx),
              );
            }, childCount: 80),
          )
        ],
      ),
    );
  }
}

class SliverTopBar extends StatelessWidget {
  const SliverTopBar(
      {Key? key, required this.extraPicHeight, required this.fitType})
      : super(key: key);
  final extraPicHeight;
  final fitType;

  @override
  Widget build(BuildContext context) {
    double rpx = MediaQuery.of(context).size.width / 750;
    return Stack(
      children: [
        Container(
          color: Theme.of(context).primaryColor,
          child: Column(
            children: [
              Image.asset(
                "assets/yujiang1.jpg",
                width: 750 * rpx,
                height: 300 * rpx + extraPicHeight,
                fit: fitType,
              ),
              Container(
                padding: EdgeInsets.only(top: 20 * rpx),
                height: 120 * rpx,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Container(
                      height: 80 * rpx,
                      width: 330 * rpx,
                      child: RaisedButton(
                        onPressed: () {},
                        child: Text(
                          "+关注",
                          style: TextStyle(
                              fontSize: 30 * rpx,
                              color: Colors.white,
                              letterSpacing: 3 * rpx),
                        ),
                        color: Colors.redAccent,
                      ),
                    ),
                    SizedBox(
                      width: 10 * rpx,
                    ),
                    Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(2 * rpx),
                        color: Color(0xff3b3c49),
                      ),
                      height: 80 * rpx,
                      child: IconButton(
                        icon: Icon(
                          Icons.arrow_drop_down,
                          color: Colors.white,
                          size: 50 * rpx,
                        ),
                        onPressed: () {},
                      ),
                    ),
                    SizedBox(
                      width: 30 * rpx,
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 100 * rpx,
              ),
              Container(
                width: 750 * rpx,
                padding: EdgeInsets.symmetric(horizontal: 30 * rpx),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "小透明",
                      style: TextStyle(
                          fontSize: 55 * rpx,
                          color: Colors.white,
                          fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "抖音号：123456",
                      style: TextStyle(
                          fontSize: 27 * rpx,
                          color: Colors.white,
                          fontWeight: FontWeight.bold),
                    ),
                    SizedBox(
                      height: 15 * rpx,
                    )
                  ],
                ),
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20 * rpx),
                child: Divider(
                  color: Colors.grey[700],
                ),
              ),
              Container(
                height: 100 * rpx,
                width: 750 * rpx,
                padding: EdgeInsets.symmetric(horizontal: 20 * rpx),
                child: Text(
                  "爱的好，安排\n大萨达大叔大婶多",
                  style: TextStyle(color: Colors.white, fontSize: 30 * rpx),
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(
                    horizontal: 20 * rpx, vertical: 10 * rpx),
                child: Row(children: [Tag(text: "杭州"), Tag(text: "上海后花园")]),
              ),
            ],
          ),
        ),
        Positioned(
          top: 240 * rpx + extraPicHeight,
          left: 30 * rpx,
          child: Container(
            width: 250 * rpx,
            height: 250 * rpx,
            child: Container(
              decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor,
                  borderRadius: BorderRadius.circular(220 * rpx)),
              padding: EdgeInsets.all(20 * rpx),
              child: CircleAvatar(
                backgroundImage: NetworkImage(
                    "https://pic2.zhimg.com/v2-a88cd7618933272ca681f86398e6240d_xll.jpg"),
              ),
            ),
          ),
        )
      ],
    );
  }
}

//用动态方法监听页面绘制后的高度
class TopBarWithCallBack extends StatefulWidget {
  const TopBarWithCallBack(
      {Key? key,
      required this.extraPicHeight,
      required this.fitType,
      required this.updateHeight})
      : super(key: key);

  final extraPicHeight;
  final fitType;
  final Function(double) updateHeight;

  @override
  State<TopBarWithCallBack> createState() => _TopBarWithCallBackState();
}

class _TopBarWithCallBackState extends State<TopBarWithCallBack>
    with AfterLayoutMixin {
  @override
  Widget build(BuildContext context) {
    return SliverTopBar(
      extraPicHeight: widget.extraPicHeight,
      fitType: widget.fitType,
    );
  }

  @override
  void afterFirstLayout(BuildContext context) {
    // TODO: implement afterFirstLayout
    RenderBox? box = context.findRenderObject() as RenderBox;
    double height =
        box.getMaxIntrinsicHeight(MediaQuery.of(context).size.width);
    widget.updateHeight(height);
    // Size size = box.size;
  }
}

class Tag extends StatelessWidget {
  const Tag({Key? key, required this.text}) : super(key: key);

  final String text;

  @override
  Widget build(BuildContext context) {
    double rpx = MediaQuery.of(context).size.width / 750;
    return Container(
      child: Container(
        child: Text(
          text,
          style: TextStyle(fontSize: 26 * rpx, color: Colors.grey[700]),
        ),
        color: Color(0xff3b3c49),
        padding: EdgeInsets.all(10 * rpx),
        margin: EdgeInsets.only(right: 10 * rpx),
      ),
    );
  }
}
